package com.ruoyi.functiontest.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.EtcGantryTreeTest;
import com.ruoyi.functiontest.service.IEtcGantryTreeTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * ETC门架区间数据测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/functiontest/EtcGantryTreeTest")
public class EtcGantryTreeTestController extends BaseController
{
    @Autowired
    private IEtcGantryTreeTestService etcGantryTreeTestService;

    /**
     * 查询ETC门架区间数据测试列表
     * 直接按照数据库存储的方式返回数据，不进行树形结构转换
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:list')")
    @GetMapping("/list")
    public AjaxResult list(EtcGantryTreeTest etcGantryTreeTest)
    {
        List<EtcGantryTreeTest> list = etcGantryTreeTestService.selectEtcGantryTreeTestList(etcGantryTreeTest);
        
        // 直接返回数据库查询结果，不进行树形结构转换
        return success(list);
    }

    /**
     * 导出ETC门架区间数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:export')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EtcGantryTreeTest etcGantryTreeTest)
    {
        List<EtcGantryTreeTest> list = etcGantryTreeTestService.selectEtcGantryTreeTestList(etcGantryTreeTest);
        ExcelUtil<EtcGantryTreeTest> util = new ExcelUtil<EtcGantryTreeTest>(EtcGantryTreeTest.class);
        util.exportExcel(response, list, "ETC门架区间数据测试数据");
    }

    /**
     * 导入ETC门架区间数据测试数据
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:import')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<EtcGantryTreeTest> util = new ExcelUtil<EtcGantryTreeTest>(EtcGantryTreeTest.class);
        List<EtcGantryTreeTest> importList = util.importExcel(file.getInputStream());
        
        // 将扁平数据转换为树形结构并保存
        String message = etcGantryTreeTestService.importEtcGantryTreeTest(importList, updateSupport);
        return success(message);
    }

    /**
     * 导入模板下载
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<EtcGantryTreeTest> templateList = new ArrayList<>();
        
        EtcGantryTreeTest example1 = new EtcGantryTreeTest();
        example1.setId(1L);
        example1.setRoadName("G1京哈高速");
        example1.setEtcCode("G1001");
        example1.setNodeName("北京-沈阳段");
        example1.setLongitude(new BigDecimal("116.4074"));
        example1.setLatitude(new BigDecimal("39.9042"));
        example1.setGantryLocation("入口");
        example1.setRemark("示例数据1");
        templateList.add(example1);
        
        EtcGantryTreeTest example2 = new EtcGantryTreeTest();
        example2.setId(2L);
        example2.setRoadName("G1京哈高速");
        example2.setEtcCode("G1001");
        example2.setNodeName("北京-沈阳段");
        example2.setLongitude(new BigDecimal("117.0000"));
        example2.setLatitude(new BigDecimal("40.0000"));
        example2.setGantryLocation("中间");
        example2.setRemark("示例数据2");
        templateList.add(example2);
        
        EtcGantryTreeTest example3 = new EtcGantryTreeTest();
        example3.setId(3L);
        example3.setRoadName("G1京哈高速");
        example3.setEtcCode("G1002");
        example3.setNodeName("沈阳-哈尔滨段");
        example3.setLongitude(new BigDecimal("123.4315"));
        example3.setLatitude(new BigDecimal("41.8057"));
        example3.setGantryLocation("出口");
        example3.setRemark("示例数据3");
        templateList.add(example3);
        
        EtcGantryTreeTest example4 = new EtcGantryTreeTest();
        example4.setId(4L);
        example4.setRoadName("G2京沪高速");
        example4.setEtcCode("G2001");
        example4.setNodeName("北京-上海段");
        example4.setLongitude(new BigDecimal("121.4737"));
        example4.setLatitude(new BigDecimal("31.2304"));
        example4.setGantryLocation("入口");
        example4.setRemark("示例数据4");
        templateList.add(example4);
        
        ExcelUtil<EtcGantryTreeTest> util = new ExcelUtil<EtcGantryTreeTest>(EtcGantryTreeTest.class);
        util.exportExcel(response, templateList, "ETC门架区间数据测试导入模板");
    }

    /**
     * 获取ETC门架区间数据测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(etcGantryTreeTestService.selectEtcGantryTreeTestById(id));
    }

    /**
     * 新增ETC门架区间数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:add')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EtcGantryTreeTest etcGantryTreeTest)
    {
        return toAjax(etcGantryTreeTestService.insertEtcGantryTreeTest(etcGantryTreeTest));
    }

    /**
     * 修改ETC门架区间数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:edit')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EtcGantryTreeTest etcGantryTreeTest)
    {
        return toAjax(etcGantryTreeTestService.updateEtcGantryTreeTest(etcGantryTreeTest));
    }

    /**
     * 删除ETC门架区间数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:remove')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (etcGantryTreeTestService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        
        return toAjax(etcGantryTreeTestService.deleteEtcGantryTreeTestByIds(ids));
    }
    
    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:fieldAudit')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = etcGantryTreeTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:ownerAudit')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = etcGantryTreeTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            EtcGantryTreeTest queryCondition = new EtcGantryTreeTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("etcCode") != null) {
                queryCondition.setEtcCode(params.get("etcCode").toString());
            }
            if (params.get("nodeName") != null) {
                queryCondition.setNodeName(params.get("nodeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = etcGantryTreeTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:EtcGantryTreeTest:centerAudit')")
    @Log(title = "ETC门架区间数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = etcGantryTreeTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = etcGantryTreeTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 构建树形结构
     */
    private List<EtcGantryTreeTest> buildTree(List<EtcGantryTreeTest> list) {
        // 构建父子关系映射
        Map<Long, EtcGantryTreeTest> nodeMap = new HashMap<>();
        List<EtcGantryTreeTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (EtcGantryTreeTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (EtcGantryTreeTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                EtcGantryTreeTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<EtcGantryTreeTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<EtcGantryTreeTest> children = (List<EtcGantryTreeTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
    
    /**
     * 处理层级数据，将第一层和第二层数据合并到第三层
     * 第一层：路段名称 -> 第三层的路段名称
     * 第二层：ETC序号、ETC门架区间、备注 -> 第三层的对应字段
     */
    private void processTreeData(List<EtcGantryTreeTest> treeList, List<EtcGantryTreeTest> exportList) {
        for (EtcGantryTreeTest level1 : treeList) {
            // 第一层数据
            String roadName = level1.getRoadName();
            
            // 处理第二层数据
            if (level1.getChildren() != null && !level1.getChildren().isEmpty()) {
                @SuppressWarnings("unchecked")
                List<EtcGantryTreeTest> level2Children = (List<EtcGantryTreeTest>) level1.getChildren();
                
                for (EtcGantryTreeTest level2 : level2Children) {
                    // 第二层数据
                    String etcCode = level2.getEtcCode();
                    String nodeName = level2.getNodeName();
                    String remark = level2.getRemark();
                    
                    // 处理第三层数据
                    if (level2.getChildren() != null && !level2.getChildren().isEmpty()) {
                        @SuppressWarnings("unchecked")
                        List<EtcGantryTreeTest> level3Children = (List<EtcGantryTreeTest>) level2.getChildren();
                        
                        for (EtcGantryTreeTest level3 : level3Children) {
                            // 将第一层的路段名称设置到第三层
                            level3.setRoadName(roadName);
                            
                            // 将第二层的ETC序号、ETC门架区间、备注设置到第三层
                            if (etcCode != null) {
                                level3.setEtcCode(etcCode);
                            }
                            if (nodeName != null) {
                                level3.setNodeName(nodeName);
                            }
                            if (remark != null) {
                                level3.setRemark(remark);
                            }
                            
                            // 添加到导出列表
                            exportList.add(level3);
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 将导入的扁平数据转换为树形结构并保存
     * @param importList 导入的扁平数据列表
     * @param updateSupport 是否支持更新已存在的数据
     * @return 导入结果消息
     */
    private String importDataToTree(List<EtcGantryTreeTest> importList, boolean updateSupport) {
        // 直接调用服务层的导入方法，确保逻辑一致性
        return etcGantryTreeTestService.importEtcGantryTreeTest(importList, updateSupport);
    }
}
